package com.itheima.service.impl;

/**
 * @author Dugen.Zhu
 * @date 2019-12-29 11:11
 */

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 套餐服务
 */
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath;//从Spring容器中取普通类型或字符串值，SpEL使用${}、#{}

    @Override
    public Result add(Setmeal setmeal, Integer[] checkgroupIds) {
        //参数校验，输入的编码或名称必须唯一，不能重复
        Setmeal _setmeal = setmealDao.findByCodeOrName(setmeal.getCode(), setmeal.getName());
        if (_setmeal != null) {
            return new Result(false, "您输入的套餐编码或名称已存在");
        } else {
            //添加检查组表数据
            setmealDao.add(setmeal);
            Integer setmealId = setmeal.getId();;
            //先校验有没有选择复选框，有就添加检查组检查项的关系表
            if (checkgroupIds != null && checkgroupIds.length > 0) {
                setmealDao.addSetmealWithGroupRelate(setmealId, checkgroupIds);
            }
            //将成功添加的套餐图片名称添加到Redis
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());

            //生成套餐列表静态页面
            List<Setmeal> setmealList = setmealDao.getAll();
            generateSetmealListHtml(setmealList);
            //生成套餐详情静态页面
            generateSetmealDetailHtml(setmealId);

            return new Result(true, MessageConstant.ADD_CHECKGROUP_SUCCESS);
        }
    }

   /* private void generateMobileStaticHtml() {
        //准备数据
        List<Setmeal> setmealList = setmealDao.getAll();
        //生成套餐列表静态页面
        generateSetmealListHtml(setmealList);
        //生成套餐详情静态页面
        generateSetmealDetailHtml(setmealList);
    }*/

    /**
     * 生成套餐列表静态页面
     *
     * @param setmealList
     */
    private void generateSetmealListHtml(List<Setmeal> setmealList) {
        Map map = new HashMap();
        map.put("setmealList", setmealList);
        generateHtml("mobile_setmeal.ftl", "m_setmeal.html", map);
        System.out.println("生成了m_setmeal.html页面");
    }

    /*private void generateSetmealDetailHtml(List<Setmeal> setmealList) {
        Map map = new HashMap();
        for (Setmeal r_setmeal : setmealList) {
            Setmeal setmeal = setmealDao.findById(r_setmeal.getId());
            map.put("setmeal", setmeal);
            generateHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + r_setmeal.getId() + ".html", map);
            System.out.println("生成了setmeal_detail_" + r_setmeal.getId() + ".html页面");
        }
    }*/

    /**
     *  生成套餐详情静态页面
     * @param setmealId
     */
    private void generateSetmealDetailHtml(Integer setmealId) {
        Map map = new HashMap();
        Setmeal setmeal = setmealDao.findById(setmealId);
        map.put("setmeal", setmeal);
        generateHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmealId + ".html", map);
        System.out.println("生成了setmeal_detail_" + setmealId + ".html页面");
    }

    private void generateHtml(String templateName, String htmlPageName, Map<String, Object> dataMap) {
        //获得配置对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer writer = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //创建页面输出目录
            File file = new File(outPutPath + htmlPageName);
            //创建输出流对象
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
            //输出
            template.process(dataMap, writer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭输出流
            try {
                if (null != writer) {
                    writer.flush();
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {

            }
        }

    }

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> page;
        if (queryString == null || queryString.length() == 0 || queryString.equals("") || queryString.trim().isEmpty()) {
            page = setmealDao.findPage();
        } else {
            page = setmealDao.findPageByCondition(queryString);
        }
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public List<Setmeal> getAll() {
        return setmealDao.getAll();
    }

    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }
}
